package com.fz.song.util;


import com.fz.song.common.Constants;
import com.fz.song.enums.ExceptionEnum;
import com.fz.song.exception.CustomException;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class CookieUtil {

    public static void saveCookie(String username, String password, HttpServletResponse response) throws Exception {
        //cookie的有效期
        long validTime = System.currentTimeMillis() + (Constants.COOKIE_VALID_TIME * 1000);
        //MD5加密用户详细信息
        String cookieValueWithMd5 = getMD5(username + ":" + password + ":" + validTime + ":" + Constants.WEB_KEY);
        //将要被保存的完整的Cookie值
        String cookieValue = username + ":" + validTime + ":" + cookieValueWithMd5;
        System.out.println("cookieValue = " + cookieValue);
        //再一次对Cookie的值进行BASE64编码
        String cookieValueBase64 = new String(Base64Utils.encode(cookieValue.getBytes()));
        //开始保存Cookie
        Cookie cookie = new Cookie(Constants.COOKIE_AUTO_LOGIN, cookieValueBase64);
        //存两年(这个值应该大于或等于validTime)
        cookie.setMaxAge(60 * 60 * 24 * 365 * 2);
        //cookie有效路径是网站根目录
        cookie.setPath("/");
        //向客户端写入
        response.addCookie(cookie);
    }


    //读取Cookie,自动完成登陆操作----------------------------------------------------------------
    public static String[] readCookie(HttpServletRequest request, HttpServletResponse response) throws CustomException {
        //根据cookieName取cookieValue
        Cookie cookies[] = request.getCookies();
        String cookieValue = null;
        if (cookies != null) {
            for (int i = 0; i < cookies.length; i++) {
                if (Constants.COOKIE_AUTO_LOGIN.equals(cookies[i].getName())) {
                    cookieValue = cookies[i].getValue();
                    break;
                }
            }
        }
        //如果cookieValue为空,返回,
        if (cookieValue == null) {
            return null;
        }
        //如果cookieValue不为空,才执行下面的代码
        //先得到的CookieValue进行Base64解码
        String cookieValueAfterDecode = null;
        try {
            cookieValueAfterDecode = new String(Base64Utils.decode(cookieValue));
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        //对解码后的值进行分拆,得到一个数组,如果数组长度不为3,就是非法登陆
        String cookieValues[] = cookieValueAfterDecode.split(":");
        if (cookieValues.length != 3) {
            response.setContentType("text/html;charset=utf-8");
            ExceptionEnum illegalLogon = ExceptionEnum.ILLEGAL_LOGON;
            throw new CustomException(illegalLogon.getCode(), illegalLogon.getMessage());
        }
        //判断是否在有效期内,过期就删除Cookie
        long validTimeInCookie = new Long(cookieValues[1]);
        if (validTimeInCookie < System.currentTimeMillis()) {
            //删除Cookie
            clearCookie(response);
            ExceptionEnum passwordExpire = ExceptionEnum.PASSWORD_EXPIRE;
            throw new CustomException(passwordExpire.getCode(), passwordExpire.getMessage());
        }
        return cookieValues;
    }


    //获取Cookie组合字符串的MD5码的字符串----------------------------------------------------------------
    public static String getMD5(String value) {
        String result = null;
        try {
            byte[] valueByte = value.getBytes();
            MessageDigest md = MessageDigest.getInstance("MD5");
            md.update(valueByte);
            result = toHex(md.digest());
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return result;
    }

    //将传递进来的字节数组转换成十六进制的字符串形式并返回
    private static String toHex(byte[] buffer) {
        StringBuffer sb = new StringBuffer(buffer.length * 2);
        for (int i = 0; i < buffer.length; i++) {
            sb.append(Character.forDigit((buffer[i] & 0xf0) >> 4, 16));
            sb.append(Character.forDigit(buffer[i] & 0x0f, 16));
        }
        return sb.toString();
    }

    //用户注销时,清除Cookie,在需要时可随时调用-----------------------------------------------------
    public static void clearCookie(HttpServletResponse response) {
        Cookie cookie = new Cookie(Constants.COOKIE_AUTO_LOGIN, null);
        cookie.setMaxAge(0);
        cookie.setPath("/");
        response.addCookie(cookie);
    }
    
}
